<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1, '0')">添加权限</el-button>
        </div>

        <el-table row-key="id" :data="permissionList" border>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addPermission(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit ? '编辑权限点' : '新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addPer">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 获取权限列表
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
// 引入转换树形结构方法
import { tranListToTreeData } from '@/utils'

export default {
  name: 'Permission',
  data() {
    // 验证权限名称是否重复，同级不能出现相同的权限名称
    const validName = (rule, value, callback) => {
      let newArr = this.originList.filter(obj => obj.pid === this.formData.pid).map(obj => obj.name)

      if (this.isEdit) {
        newArr = this.originList.filter(obj => obj.pid === this.formData.pid && obj.id !== this.formData.id).map(obj => obj.name)
      }

      newArr.includes(value.trim()) ? callback(new Error(value + '已存在')) : callback()
      // // 先找兄弟节点
      // let existList = this.originList.filter(item => {
      //   item.pid === this.formData.pid
      // })
      // if (this.isEdit) {
      //   // 编辑时排除自身
      //   existList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      // }
      // existList.map(item => item.name.trim()).includes(value) ? callback(new Error(`权限名称${value}已存在`)) : callback()
    }

    // 验证权限标识是否重复
    const validCode = (rule, value, callback) => {
      // let newArr = this.originList.map(obj => obj.code)
      // // console.log(newArr)
      // console.log(this.isEdit)
      // if (this.isEdit) {
      //   newArr = this.originList.filter(obj => obj.id !== this.formData.id).map(obj => obj.code)
      // }
      // newArr.includes(value) ? callback(new Error(value + '已存在')) : callback()
      // 新增时的校验
      // 获取模块所有数据
      let existCodeList = this.originList

      // 编辑时的校验
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }

      // 将所有数据中的code组成一个数组
      // 使用includes验证输入的标识在不在code数组中

      existCodeList.map(item => item.code).includes(value) ? callback(new Error(`权限标识${value}已存在`)) : callback()
    }
    return {
      permissionList: [], // 权限管理列表数据
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isEdit: false,
      originList: [] // 精简之后的数据
    }
  },

  created() {
    // 调用获取权限管理列表的数据
    this.getPermissionList()
  },

  methods: {
    // 删除权限点
    async delPermission(id) {
      // 使用询问框组件
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果点击了取消
      if (confirmRes === 'cancel') return
      // 否则调用API
      const res = await delPermission(id)
      // 给用户提示，刷新列表
      this.$message.success(res.message)
      this.getPermissionList()
    },

    // 编辑权限点
    async editPermission(id) {
      // 调用API
      const res = await getPermissionDetail(id)
      // 数据回显
      this.formData = res.data

      // 展示弹框
      this.showDialog = true
      // 编辑状态
      this.isEdit = true
    },

    // 点击确定添加权限
    addPer() {
      // 兜底验证
      this.$refs.perForm.validate(async valid => {
        // 失败，直接return
        if (!valid) return

        if (!this.isEdit) {
          // 成功，调用API
          const res = await addPermission(this.formData)
          // 给用户提示
          this.$message.success(res.message)
        } else {
          const res = await updatePermission(this.formData)
          this.$message.success(res.message)
        }

        // 关闭弹框
        this.showDialog = false
        // 刷新列表
        this.getPermissionList()
      })
    },

    // 添加权限
    addPermission(type, pid) {
      // 记录当前关键字信息
      this.formData.type = type
      this.formData.pid = pid
      // 弹框展示
      this.showDialog = true

      // isEdit -> false
      this.isEdit = false
    },

    // 点击取消关闭弹层
    btnCancel() {
      // 重置表单
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }

      this.$refs.perForm.resetFields()

      this.showDialog = false
    },

    // 获取权限管理列表的数据
    async getPermissionList() {
      const res = await getPermissionList()

      // 将自定义验证函数使用的数据进行精简
      this.originList = res.data.map(item =>
        ({
          id: item.id,
          pid: item.pid,
          name: item.name,
          code: item.code
        }))
      // console.log(this.originList)

      this.permissionList = tranListToTreeData(res.data)
    }
  }
}
</script>

<style lang="scss" scoped></style>

